import { deleteByColumnInfoId, getliveStreamingDetail, getyouhui, getloudetail, getdetails, unpublish, saveAndPublish, keepActiveAerea, regionArea, getactiveList, parentCode, getEstateList, getCouponsList, getliveStreamingList } from './activityAreaDetailServ'
// 弹出消息框
import { message } from 'antd'
import { parse } from 'qs'
import { download } from 'utils/util'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import { call } from 'file-loader'

// 初始默认状态
const state = {
    published: 0, //发布状态
    activityDetail: {},
    typeChange: '',
    Enroll: {},
    areaList: [],
    estateList: [],
    estateListopt: [],
    primeList: [],
    willDetail: {},
    detail: {
        columnInfoTitle: '',
        columnInfoType: '',
        content: []
    },
    rcolumnTypeList: [
        { name: '楼盘', value: 1 },
        { name: '优惠券', value: 2 },
        { name: '直播', value: 5 },
        { name: '视频', value: 3 },
        { name: '报名活动', value: 4 }
    ],
    gif: [
        { eyeisShow: false, source: 'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/activityArea/oneUI.jpg', style: '0' },
        { eyeisShow: false, source: 'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/activityArea/twoUI.jpg', style: '1' },
        { eyeisShow: false, source: 'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/activityArea/threeUI.jpg', style: '2' }
    ],
    openImg: false,
    openImgSrc: '',
    // 栏目楼盘
    builddingList: [],
    CouponList: [],
    discountCouponList: [], //优惠券列表
    StreamingList: [],
    liveStreamingList: [], //直播列表
    recordVideoUrlArr: [],
    actionType: '',
    columnInfoList: [], //栏目信息列表
    acttiveList: [], //活动列表
    acttives: [],
    columnType: 'add', //栏目状态，add增加、edit编辑
    editColumnIndex: null, //修改栏目的索引
    area1: [],
    areas: [],
    activityAreaId: '',
    modalIsOpen: false,
    editorState: '',
    lanmus: 0,
    setHouse: ['', '', '', '']
}

const tmpModule = {
    // namespace: 'infoAddOrEditModel',
    state: cloneDeep(state),
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname, query }) => {
                let { actionType, activityAreaId } = query
                if ('' + tmpModule.pathname === '' + pathname) {
                    //每次进来页面更新数据 重置state
                    dispatch({ type: 'updateStore', payload: cloneDeep(state) });
                    dispatch({ type: 'updateStore', payload: { actionType, activityAreaId, roleType: localStorage.getItem('roleType') } });
                    dispatch({ type: 'regionArea', payload: {} });
                    dispatch({ type: 'getAreaList' })
                    dispatch({ type: 'getCouponsList' })
                    dispatch({ type: 'getliveStreamingList' })
                    dispatch({ type: 'getactiveList' })
                    if (actionType != 'add') {
                        dispatch({ type: 'getdetail', payload: { activityAreaId, actionType } })
                    }

                }
            })
        },
    },
    effects: {
        // 所属区域
        * regionArea({ payload }, { put, call, select }) {
            let { activityDetail, areas } = yield select(state => state[tmpModule.namespace])
            const { success, data } = yield call(regionArea)
            if (success) {
                if (activityDetail.regionId) {
                    data.map((item, index) => {
                        if (item.value == activityDetail.regionId) {
                            areas = makeAddress(item.children, 2)
                            areas.shift()
                        }
                    })
                    yield put({
                        type: 'getProduct',
                        payload: {}
                    })
                }
                yield put({ type: 'updateStore', payload: { area1: data, areas } })
            }
        },
        //获取级联列表
        * getAreaList({ payload }, { put, call, select }) {
            try {
                const { data, success } = yield call(parentCode);
                if (success) {
                    let areaList = [],
                        builddingList = [];
                    let arr = [data[0]]
                    let attr = [data[data.length - 1]]
                    data[0] = {
                        label: "北京",
                        value: "110100",
                        children: arr
                    }
                    data[data.length - 1] = {
                            label: "澳门",
                            value: "820000",
                            children: attr
                        }
                        //去掉第三级，
                    areaList = makeAddress(data, 2)
                        // builddingList.push({
                        //     areaList
                        // })
                    yield put({ type: 'updateStore', payload: { areaList } });
                }
            } catch (e) {

            }
        },
        //获取项目列表
        * getBusinessList({ payload }, { put, call, select }) {
            let params = {
                pageNo: 1,
                pageSize: 10000,
                province: payload.province,
                city: payload.city,
                shelfStatus: 1
            }
            try {
                const data = yield call(getEstateList, params)
                let { estateListopt } = yield select(state => state[tmpModule.namespace])
                let estateList = []
                if (data.success) {
                    estateList = data.rows
                }
                estateListopt[payload.index] = estateList
                    // builddingList[payload.index].estateList = estateList
                yield put({ type: 'updateStore', payload: { estateListopt } });
            } catch (e) {

            }
        },
        // 获取楼盘详情信息
        * getloudetail({ payload }, { put, call, select }) {
            try {
                const { data, success } = yield call(getloudetail, {
                    productId: payload.productId
                });
                let { builddingList, detail } = yield select(state => state[tmpModule.namespace])
                if (success) {
                    // 存在标签内容，所以要合并对象
                    builddingList[payload.index] = Object.assign(builddingList[payload.index], data)
                    detail['content'] = builddingList
                    console.log('neris', detail)
                    yield put({ type: 'updateStore', payload: { builddingList, detail } });
                }
            } catch (e) {

            }
        },
        //获取优惠券列表
        * getCouponsList({ payload }, { put, call, select }) {
            try {
                //admin/coupons/config/list
                const { rows, success } = yield call(getCouponsList, {
                    pageNo: 1,
                    status: "2",
                    pageSize: 100000,
                    ...payload
                });
                let CouponList = []
                if (success) {
                    if (rows) {
                        CouponList = rows;
                        yield put({ type: 'updateStore', payload: { CouponList } });
                    }
                }
            } catch (e) {

            }
        },
        // 获取优惠券详情
        * getyouhui({ payload }, { put, call, select }) {
            const { data, success } = yield call(getyouhui, {
                id: payload.id
            });
            let { discountCouponList, detail } = yield select(state => state[tmpModule.namespace])
            if (success) {
                discountCouponList[payload.index] = data
                detail['content'] = discountCouponList
                yield put({ type: 'updateStore', payload: { discountCouponList, detail } });
            }

        },
        //获取直播列表
        * getliveStreamingList({ payload }, { put, call, select }) {
            //admin/coupons/config/list
            const { rows, success } = yield call(getliveStreamingList, {
                published: 1,
                pageNo: 1,
                pageSize: 10,
                ...payload
            });
            let StreamingList = []
            if (success) {
                if (rows) {
                    StreamingList = rows;

                } else {
                    StreamingList = []
                }
                yield put({ type: 'updateStore', payload: { StreamingList } });
            }
        },
        // 获取直播详情
        * getliveStreamingDetail({ payload }, { put, call, select }) {
            const { data, success } = yield call(getliveStreamingDetail, {
                id: payload.id
            });
            let { liveStreamingList, detail } = yield select(state => state[tmpModule.namespace])
            if (success) {
                liveStreamingList[payload.index] = data
                detail['content'] = liveStreamingList
                yield put({ type: 'updateStore', payload: { liveStreamingList, detail } });
            }

        },
        * getactiveList({ payload }, { put, call, select }) {
            const { rows, success } = yield call(getactiveList, {
                pageNo: 1,
                channel: 3,
                status: "1",
                published: 1,
                pageSize: 100000,
                ...payload
            });
            let acttives = []
            if (success) {
                if (rows) {
                    acttives = rows;
                    yield put({ type: 'updateStore', payload: { acttives } });
                }
            }
        },
        // 保存|发布|取消发布
        * submit({ payload }, { put, call, select }) {
            // 保存
            if (payload.type == 'save') {
                let { data, success, msg } = yield call(keepActiveAerea, payload.activityDetail)
                if (success) {
                    message.success('保存成功')
                    hashHistory.push({ pathname: '/home/infoAdmin/activityAreaList' })
                } else {
                    message.error(msg)
                }
            } else if (payload.type == 'saveAndPublish') {
                let { data, success, msg } = yield call(saveAndPublish, payload.activityDetail)
                if (success) {
                    message.success('保存并发布成功')
                    hashHistory.push({ pathname: '/home/infoAdmin/activityAreaList' })
                } else {
                    message.error(msg)
                }
            } else if (payload.type == 'unpublish') {
                let { activityAreaId } = yield select(state => state[tmpModule.namespace])
                let { data, success, msg } = yield call(unpublish, payload)
                if (success) {
                    // yield put({ type: 'getdetail', payload: { activityAreaId } })
                    message.success('已取消发布')
                    hashHistory.push({ pathname: '/home/infoAdmin/activityAreaList' })
                } else {
                    message.error(msg)
                }
            }

        },
        * updateModel({ payload }, { put, select }) {
            yield put({ type: 'updateStore', payload });
        },
        // 查看详情
        * getdetail({ payload }, { put, call, select }) {
            let { data, success } = yield call(getdetails, { activityAreaId: payload.activityAreaId })
            let { lanmus } = yield select(state => state[tmpModule.namespace])
            if (success) {
                if (data instanceof Object && JSON.stringify(data) != '{}') {
                    // 活动规则富文本回显
                    // const contentBlock = htmlToDraft(data.activityAreaRule);
                    // const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
                    // const editorState = EditorState.createWithContent(contentState);
                    if (payload.actionType == 'edit') {
                        lanmus = data.columnInfoList[data.columnInfoList.length - 1].number
                    }
                    console.log('交给警1', data.columnInfoList)
                        // for (let a = 0; a < data.columnInfoList.length; a++) {
                        //     if (data.columnInfoList[a]['columnInfoType'] === 1) {
                        //         let cont = JSON.parse(data.columnInfoList[a].content)
                        //         console.log('cont', cont)
                        //         for (let b = 0; b < cont.length; b++) {
                        //             console.log('a', cont[b].hasOwnProperty('houseTags'))
                        //             if (!cont[b].hasOwnProperty('houseTags')) {
                        //                 cont[b].houseTags = ['', '', '', '']
                        //                 data.columnInfoList[a].content = JSON.stringify(cont)
                        //             }
                        //         }
                        //     }
                        // }
                    console.log('交给警3', data.columnInfoList)
                    yield put({
                        type: 'updateStore',
                        payload: {
                            published: data.status,
                            activityDetail: data,
                            columnInfoList: data.columnInfoList,
                            lanmus
                        }
                    });
                }
            }
        },
        // 删除栏目
        * deleteByColumnInfoId({ payload }, { put, call, select }) {
            let { data, success } = yield call(deleteByColumnInfoId, payload)
        },
    },

    // 存入状态机
    reducers: {
        updateStore(preState, action) {
            return {...preState, ...action.payload };
        }
    }
}

export default tmpModule